#!/bin/bash

if [[ -z "$1" ]]
then
	echo "[*] usage: $(basename $0)  duckload-url"
	exit
fi

url="$1"

agent="Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322)"
cookie="cookie.txt"
base_url="http://www.duckload.com/jDownloader"

url_checkOnlineStatus="$base_url/checkOnlineStatus.php"
url_getFree="$base_url/getFree.php"
url_getFreeEncrypt="$base_url/getFreeEncrypt.php"

RED='\e[1;31m'
CYAN='\e[0;36m'
NC='\e[0m' # No Color

echo -e "$RED [*] checking online status $NC"
status=$(curl \
		--silent \
		--user-agent "$agent" \
		--data-urlencode "isPremium=0" \
		--data-urlencode "list=$url" "$url_checkOnlineStatus" \
		--output -)

echo $status
if [[ ! "$status" =~ "SUCCESS" ]]
then
	exit -1
fi

echo -e "$RED [*] getting free slots $NC"
status=$(curl \
	--silent \
	--user-agent "$agent" \
	--referer "$url_checkOnlineStatus" \
	--data-urlencode "link=$url" "$url_getFree" \
	--output -)

echo $status
if [[ ! "$status" =~ "SUCCESS" ]]
then
	exit -1
fi

time=$(echo "$status" | awk -F "; " "{print \$2}")
crypt=$(echo "$status" | awk -F "; " "{print \$3}")

echo -e "$RED [*] free user delay $NC"
count=0
for i in $(seq 1 1 $time)
do
	#sleep 1
	count=$((count+1))
	echo -n "$((time-count)) "
done
echo

echo -e "$RED [*] getting final url $NC"
status=$(curl \
	--silent \
	--user-agent "$agent" \
	--referer "$url_getFree" \
	--data-urlencode "crypt=$crypt" "$url_getFreeEncrypt" \
	--output -)

echo $status
if [[ ! "$status" =~ "ERROR" ]] && [[ "$status" =~ "http" ]]
then
	echo -e "$RED [*] starting download ... $NC"
	if [[ -x $(which axel) ]]
	then
		axel "$status"
	else
		wget "$status"
	fi
fi

